<?php
class Category_Model extends MY_Model {
	var $_table = "categories";
	var $_table_meta = "categories_meta";
	var $_field_meta_rel = "category_id";
	
	function Category_Model(){
		parent::Model();
	}
	
	function _getTree($categories, $parentId=0){
		$treeCategories = array();
		
		foreach($categories as $category){
			if($category->parent_id == $parentId){
				$category->categories = array();
				
				$treeCategoriesTemp = $this->_getTree($categories, $category->id);
				if(count($treeCategoriesTemp)>0){
					$category->categories = $treeCategoriesTemp;
				}
				array_push($treeCategories, $category);
			}
		}
		
		return $treeCategories;
	}
	
	function create($fields){
		//TODO tratar el titulo de las categorias multiidioma (PROPIEDAD TITLE con multitiidoma?)
		$fields['url_name'] = $this->getValidUrlName($fields['url_name']);
		
		$data = array (
			'parent_id' => $fields['parent_id'],
			'name' 		=> $fields['name'],
			'url_name' 	=> $fields['url_name'],
			'visible'	=> $fields['visible']
		);

		$this->db->insert($this->_table, $data);
		
		$id = $this->db->insert_id();
		
		$this->_regenerate_parents();
		
		return $id; 		
	}


	function update($fields){

		$category = $this->get(array("id" => $fields['id'], "status" => "all"));
		
		if($category != NULL){
			
			// @TODO revisar
			if($fields['url_name'] != $category->url_name){
				$fields['url_name'] = $this->getValidUrlName($fields['url_name']);
			}
			
			$data = array (
				'parent_id' => $fields['parent_id'],
				'name' 		=> $fields['name'],
				'url_name' 	=> $fields['url_name'],
				'visible'	=> $fields['visible']
			);
	
			$this->db->where('id', $fields['id']);
			$this->db->update($this->_table, $data);
		}
		
		$this->_regenerate_parents();
		
	}
	
	function _regenerate_parents($parent_id = 0, $parents = "", $parents_name = ""){
		$this->db->from ( $this->_table );
		$this->db->where("parent_id", $parent_id);
		$query = $this->db->get ();
		$categories = $query->result ();
		
		foreach($categories as $category){
			
			//update
			$this->db->where('id', $category->id);
			$this->db->update($this->_table, array(
				"parents" => $parents, 
				//"parents_name" => $parents_name
			));
			
			$new_parents = $parents . "_{$category->id}_";
			$new_parents_name = $parents_name . "__{$category->url_name}__";
			$this->_regenerate_parents($category->id, $new_parents, $new_parents_name);
			
		}
		
	}
	
	function delete($id){
		$categorias = $this->get(array("parent" => $id, "status" => "all"));
		if($categorias !== FALSE){
			foreach($categorias as $cat){
				$this->delete($cat->id);
			}
		}
		
		$this->db->where('id', $id);			
		$this->db->delete($this->_table);
		
		$this->db->delete($this->_table_meta, array($this->_field_meta_rel => $id));
		
		$this->db->where('id_category', $id);			
		$this->db->delete("nodes_categories");
		
		$this->_regenerate_parents();
	}
	
	
	function get($params = array(), $start = -1, $offset = -1){
		$params = $this->_getParams($params);
		
		/*$cache_time = intval($this->settings->item("_site_cache_categories_time"));
		
		if((!defined("IS_ADMIN") || !IS_ADMIN) && $cache_time){
		
			$param_serialize = md5(serialize($params) . "start:$start.offset:$offset");
			
			$data_cache = $this->mp_cache->set_name("category/$param_serialize")->get();
			if ($data_cache !== FALSE){
				return $data_cache;
			}
		}*/
		
		$data_cache = NULL;
		
		$DB = $this->_get($params);
		
		$DB->select ( $this->_table . ".*" );
		
		if ($start != - 1 && $offset != - 1) {
			$DB->limit ( $offset, $start );
		}
		
		$query = $DB->get ();
		
		if((isset($params['id']) && $params['id'] != NULL && $params['id'] !=-1) ||
			(isset($params['url_name']) && $params['url_name'] != NULL)){
				
			if ($query->num_rows() > 0){
				$data_cache = $query->row();
			} else{
				$data_cache = NULL;
			}
				
		} else if (($params['hierarchical'] || $params['parent']) && $query->num_rows() > 0){
			//montamos el arbol
			$categories = $query->result();
			
			
			$treeCategories = array();
			
			if($params['parent'] != NULL && $params['parent'] != -1){
				$treeCategories = $this->_getTree($categories, $params['parent']);
			} else{
				$treeCategories = $this->_getTree($categories);
			}
			
			if($params["hierarchical"]){
				$data_cache = $treeCategories;
			} else{
				$data_cache = $categories;
			}
			
		} else{
			$data_cache = $query->result ();
		}
		
		/*if((!defined("IS_ADMIN") || !IS_ADMIN) && $cache_time){
			$this->mp_cache->set_contents($data_cache)->set_expires($cache_time)->write();
		}*/
		
		return $data_cache;
	}
	
	function getCount($params = array()){
		$params = $this->_getParams($params);
		$params["num_nodes"] = FALSE;
		$DB = $this->_get($params);

		return $DB->count_all_results ();
	}
	
	function _getParams($params = array()){
		$defaults = array(
			"id"			=> NULL,
			"url_name"		=> NULL,
			"status" 		=> "visible", //no_visible, all		
			"hide_empty"	=> FALSE,
			"hierarchical"	=> TRUE,		
			//"child_of"		=> NULL,
			"parent"		=> NULL, 
		
			"num_nodes"		=> FALSE,
		 
			"order"			=> array(
				"name"	=> "asc"
			)
		);
		
		$params = array_merge($defaults, $params);
		
		return $params;
	}
	
	function _get($params  = array()){
		$this->db->from ( $this->_table );
		
		if($params['status'] != NULL && $params['status'] != "all" ){
			if($params['status'] == "visible"){
				$this->db->where("$this->_table.visible = 1");
			} else if($params['status'] == "no_visible"){
				$this->db->where("$this->_table.visible = 0");
			}
		}
		
		if($params['id'] != NULL && $params['id'] != -1){
			$this->db->where ( "$this->_table.id", $params['id'] );
		} else if($params['url_name'] != NULL && $params['url_name'] != ""){
			$this->db->where ( "{$this->_table}.url_name", $params['url_name'] );
		} else{
			
			//@TODO resto de filtros
			if($params['parent'] != NULL){
				if(is_numeric($params['parent'])){
					$this->db->like ( "{$this->_table}.parents", "_{$params['parent']}_" );
				} else{
					$this->db->like ( "{$this->_table}.parents_name", "__{$params['parent']}__" );
				}
				
			}
			
			if($params['order'] != NULL){
				foreach($params['order'] as $field => $direction){
					$this->db->order_by ( "$field $direction" );
				}
			}
			
			if($params['num_nodes'] || $params['hide_empty']){
				if($params['hide_empty']){
					$this->db->join("nodes_categories", "nodes_categories.id_category={$this->_table}.id");
				} else{
					$this->db->join("nodes_categories", "nodes_categories.id_category={$this->_table}.id", "left");
				}
								
				$this->db->group_by("{$this->_table}.id");
				
				$this->db->select("COUNT(nodes_categories.id_node) AS num_nodes");
				
			}
		}
		
		return $this->db;
	}
	
	
	/*
	function getChildsById($id){
		$this->db->from($this->_table);
		$this->db->where("parent_id", $id);
		
		$query = $this->db->get ();	
		if ($query->num_rows() > 0){
			return $query->result();
		}	

		return FALSE;
	}

	function getDescendantsById($id = -1){
		$this->db->from($this->_table);
		
		$query = $this->db->get ();	
		if ($query->num_rows() > 0){
			//montamos el arbol
			$categories = $query->result();
			
			$descendantsCategories = $this->_getDescendants($categories, $id);
			
			return $descendantsCategories;
			
		}

		return FALSE;	
	}
	
	function _getDescendants($categories, $parentId=-1){
		$categoriesTemp = array();
		
		foreach($categories as $category){
			if($category->parent_id == $parentId){
				$category->categories = array();
				
				$categoriesTempAux = $this->_getDescendants($categories, $category->id);
				if(count($categoriesTempAux)>0){
					foreach($categoriesTempAux as $cat){
						array_push($categoriesTemp, $cat);
					}
				}
				array_push($categoriesTemp, $category);
			}
		}
		
		return $categoriesTemp;
	}
	
	function getDescendantTreeByUrlName($name = ""){
		if($name != ""){
			$category = $this->getByUrlName($name);
			if($category !== FALSE){
				return $this->getDescendantTreeById($category->id);
			}
		}
		return FALSE;
	}
	
	function getDescendantTreeById($id = -1){
		$this->db->from($this->_table);
		
		$query = $this->db->get ();	
		if ($query->num_rows() > 0){
			//montamos el arbol
			$categories = $query->result();
			
			$treeCategories = $this->_getTree($categories, $id);
			
			return $treeCategories;
			
		}

		return FALSE;
	}
	*/
	
	/*
	function getAll(){
		$this->db->from($this->_table);
		
		$query = $this->db->get ();	
		if ($query->num_rows() > 0){
			return $query->result();
		}

		return FALSE;	
	}
	
	function getById($id){
		$this->db->from($this->_table);
		$this->db->where("id", $id);
		
		$query = $this->db->get ();	
		if ($query->num_rows() > 0){
			return $query->row();
		}	

		return FALSE;
	}
	
	function getByUrlName($urlName){
		$this->db->from($this->_table);
		$this->db->where("url_name", $urlName);
		
		$query = $this->db->get ();	
		if ($query->num_rows() > 0){
			return $query->row();
		}	

		return FALSE;
	}
	*/
}
?>
